package com.example.plugindemo;

import android.app.ActivityManager;
import android.os.Build;
import android.os.Handler;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

public class HookHelper {

    public static final String TARGET_INTENT="target_intent";

    public static void hookAMS() throws Exception{
        Object defaultSingleton = null;
        if(Build.VERSION.SDK_INT>=26){
            Class activityManagerClazz = Class.forName("android.app.ActivityManager");
            defaultSingleton = FieldUtil.getField(activityManagerClazz,null,"IActivityManagerSingleton");
        }

        Class singletonClazzz = Class.forName("android.util.Singleton");
        Field mInstanceField = FieldUtil.getField(singletonClazzz,"mInstance");

        Object iActivityManager = mInstanceField.get(defaultSingleton);

        Class iActivityManagerClazz = Class.forName("android.app.IActivityManager");

        Object iActivityManagerProxy = Proxy.newProxyInstance(iActivityManagerClazz.getClassLoader(),new Class[]{iActivityManagerClazz},new IActivityManagerProxy(iActivityManager));

        mInstanceField.set(defaultSingleton,iActivityManagerProxy);

    }

    public static void hookHandler() throws Exception{

        Class activityThreadClazz = Class.forName("android.app.ActivityThread");

        Object currentActivityThread =FieldUtil.getField(activityThreadClazz,null,"sCurrentActivityThread");

        Handler mH = (Handler) FieldUtil.getField(activityThreadClazz,currentActivityThread,"mH");

        FieldUtil.setField(Handler.class,mH,"mCallback",new HCallback(mH));

    }
}
